package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UsrService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class UserServiceImpl implements UsrService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
       /*
      service 做什么
        1: 解析出code授权码
        找微信 发送校验请求
        https://api.weixin.qq.com/sns/jscode2session  get
        参数
         appid  secret  从 weChatProperties 获取
         js_code  userLoginDTO获取
         grant_type authorization_code
       2:结果---json里面有openid就算成功  openid是null 没有就是失败
           {
                "session_key": "l3YGHGkZnKkupxmcuUA5GQ==",
                "openid": "o1ybQ6rjMYEJa508hN_JzdZNjk08"
            }
           {
                "errcode": 40029,
                "errmsg": "invalid code, rid: 671b478d-57513cef-2c823d24"
            }
       3:失败--抛出异常 --- 自定义异常LoginFailedException
       4:校验成功 有 openId了
          根据openid去数据库查询 用户信息
          查到 User 不是null 已经有了  有id 有openid
          没查到 User null 新用户 设置openid 完成新增 回显主键 因为要id
      5: 最终返回user对象
     */

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {

            log.info("UserLoginDTO信息:{}",userLoginDTO);
            // 1：解析出code授权码
            String code = userLoginDTO.getCode();
            //请求路径
            String url = "https://api.weixin.qq.com/sns/jscode2session";
            //请求参数 map集合
            Map<String, String> map = new HashMap<>();
            map.put("appid", weChatProperties.getAppid());
            map.put("secret", weChatProperties.getSecret());
            map.put("js_code", code);
            map.put("grant_type", "authorization_code");
            //发请求
            String json = HttpClientUtil.doGet(url, map);
            //json字符串数据
            JSONObject jsonObject = JSON.parseObject(json);
            //获取openid
            String openid = jsonObject.getString("openid");
            //3:校验失败 抛出异常
            if (openid == null) {
                throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
            }
            //4:校验成功 有 openId了
            //4.1 根据openId查询 user表
            User user = userMapper.getByOpenId(openid);

            //4.2 如果是null
            if (user == null) {//得新增
                user = new User();
                user.setOpenid(openid);
                user.setCreateTime(LocalDateTime.now());
                userMapper.insert(user);
            }

            return user;

        }
    }
